import { Injectable, HttpException, HttpStatus } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, In } from 'typeorm';
import { Tag } from '../../entities/tag.entity';

@Injectable()
export class TagService {
  constructor(
    @InjectRepository(Tag)
    private tagRepository: Repository<Tag>,
  ) {}

  async findAll() {
    // 只返回启用的标签
    return this.tagRepository.find({ 
      where: { isActive: 1 },
      order: { usageCount: 'DESC' } 
    });
  }

  async findAllAdmin() {
    // 返回所有标签，包括已禁用的
    return this.tagRepository.find({ order: { usageCount: 'DESC' } });
  }

  async findOne(id: number) {
    return this.tagRepository.findOne({ where: { id } });
  }

  async findByName(name: string) {
    return this.tagRepository.findOne({ where: { name } });
  }

  async create(tagData: Partial<Tag>) {
    const tag = this.tagRepository.create(tagData);
    return this.tagRepository.save(tag);
  }

  async update(id: number, tagData: Partial<Tag>) {
    await this.tagRepository.update(id, tagData);
    return this.tagRepository.findOne({ where: { id } });
  }

  async remove(id: number) {
    // 先解除与所有文章的关联（通过SQL直接操作关联表）
    await this.tagRepository.query(`
      DELETE FROM article_tags_tag 
      WHERE tagId = ?
    `, [id]);
    
    // 然后删除标签
    await this.tagRepository.delete(id);
    return { success: true };
  }

  async updateUsageCount() {
    // 获取所有标签并更新其使用次数
    const tags = await this.tagRepository.find();
    
    for (const tag of tags) {
      // 查询该标签关联的文章数量
      const countQuery = `
        SELECT COUNT(*) as count 
        FROM article_tags_tag 
        WHERE tagId = ?
      `;
      const result = await this.tagRepository.query(countQuery, [tag.id]);
      const usageCount = result[0].count || 0;
      
      // 更新标签使用次数
      tag.usageCount = usageCount;
      await this.tagRepository.save(tag);
    }
  }

  async getPopularTags(limit: number = 10) {
    return this.tagRepository.find({
      order: { usageCount: 'DESC' },
      take: limit,
    });
  }

  // 通过ID数组查找标签
  async findByIds(ids: number[]) {
    return this.tagRepository.find({
      where: { id: In(ids) }
    });
  }

  async updateStatus(id: number, isActive: number) {
    // 检查标签是否存在
    const tag = await this.tagRepository.findOne({ where: { id } });
    if (!tag) {
      throw new HttpException('标签不存在', HttpStatus.NOT_FOUND);
    }

    // 更新状态
    await this.tagRepository.update(id, { isActive });
    
    // 返回更新后的标签
    return this.tagRepository.findOne({ where: { id } });
  }
}
